package org.ispider.fb;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import org.codehaus.groovy.grails.web.json.JSONArray;
import org.codehaus.groovy.grails.web.json.JSONObject;
import org.ispider.Utils;

public class FetchFacebookJson {
	private StringBuffer fbSearchUrl = new StringBuffer();
	private String returnValue;
	private String q;
	public static final int TIMEOUT = 1000;

	public static ArrayList<FBInfo> getFacebookData(String query) {
		FetchFacebookJson fb = new FetchFacebookJson();
		fb.q = query.replaceAll("\\s", "+").toLowerCase();
		fb.fbSearchUrl.append("https://graph.facebook.com/search?q=" + fb.q
				+ "&type=post");
		try {
			fb.returnValue = fb.readUrl(fb.fbSearchUrl.toString());
		} catch (Exception e) {
			 e.printStackTrace();
		}
		return (fb.parseFbStatus(fb.returnValue));
	}

	private String readUrl(String urlString) throws Exception {
		StringBuilder response = new StringBuilder();

		URL url = new URL(urlString);
		HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();
		if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
			BufferedReader input = new BufferedReader(new InputStreamReader(
					httpconn.getInputStream()), 8192);
			String strLine = null;
			while ((strLine = input.readLine()) != null) {
				response.append(strLine);
			}
			input.close();
		}
		return response.toString();
	}

	private ArrayList<FBInfo> parseFbStatus(String response) {
		ArrayList<FBInfo> statusInfo = new ArrayList<FBInfo>();
		JSONObject object = new JSONObject(response);
		JSONArray array = object.getJSONArray("data");
		for (int i = 0; i < array.length(); i++) {
			try {
				FBInfo fb = new FBInfo();
				String message = array.getJSONObject(i).getString("message");
				
				JSONObject from = array.getJSONObject(i).getJSONObject("from");
				if (from.getString("name") != null) {
					fb.setFromName(from.getString("name"));
				} else {
					fb.setFromName(" ");
				}
				String id = array.getJSONObject(i).getString("id");
				String[] ids = id.split("_");
				fb.setUserID(ids[0]);
				fb.setPostID(ids[1]);
				String url = "http://www.facebook.com/" + ids[0] + "/posts/"
						+ ids[1];
				fb.setUrlString(url);
				if (message != null) {
					String[] keywords = q.split("\\+");
					for (String s : keywords)
						message = message.replaceAll("(?i)" + s, "<b>" + s
								+ "</b>");
					fb.setStatusMessage(Utils.makeLinks(message,url));
				}
				String picture = array.getJSONObject(i).getString("picture");
				fb.setPicture(picture);
				String updatetime = array.getJSONObject(i).getString(
						"updated_time");
				fb.setCreatedTime(updatetime);
				String userURLString = "http://www.facebook.com/" + ids[0];
				fb.setUserURLString(userURLString);
				statusInfo.add(fb);
			} catch (Exception ex) {
			}

		}
		return statusInfo;
	}

}
